package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 处理 Exel 文件
 * 
 * @author SDZJ
 *
 */
public class ExcelUtil {

	private int totalRows;
	private int totalCells;

	/**
	 * 根据文件名读取excel文件
	 * 
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public List<List<String>> read(String fileName) {
		List<List<String>> dataLst = null;//new ArrayList<ArrayList<String>>();

		/* 检查文件是否存在 */
		File file = new File(fileName);
		if (file == null || !file.exists()) {
			return dataLst;
		}

		/* 检查文件名是否 Excel 格式的文件 */
		String fn = fileName.substring(fileName.lastIndexOf(File.separator)+1);
		if (!fn.matches("^.+\\.(?i)((xls)|(xlsx))$")) {
			return dataLst;
		}

		boolean isExcel2003 = true;
		/* 对文件的合法性进行验证 */
		if (fn.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}


		try {
			/** 调用本类提供的根据流读取的方法 */
			dataLst = read(new FileInputStream(file), isExcel2003);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		/** */
		/** 返回最后读取的结果 */
		return dataLst;
	}

	/**
	 * 根据流读取Excel文件
	 * 
	 * @param inputStream
	 * @param isExcel2003
	 * @return
	 */
	public List<List<String>> read(InputStream inputStream, boolean isExcel2003) {
		List<List<String>> dataLst = null;
		try {
			/* 根据版本选择创建Workbook的方式 */
			Workbook wb = isExcel2003 ? new HSSFWorkbook(inputStream)
					: new SXSSFWorkbook(new XSSFWorkbook(inputStream),1000);
			dataLst = read(wb);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataLst;
	}

	private List<List<String>> read(Workbook wb) {
		List<List<String>> dataLst = new LinkedList<List<String>>();

		/* 得到第一个shell */  
		Sheet sheet = wb.getSheetAt(0);
		this.totalRows = sheet.getLastRowNum()+1;
		if (this.totalRows >= 1 && sheet.getRow(0) != null) {
			this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
		}
//		for(int i=0;i<this.totalRows;i++){
//			Row row = sheet.getRow(i);
//			if(row==null){
//				row = sheet.createRow(i);
//			}
//		}
		/* 循环Excel的行 */
		for (int r = 0; r < this.totalRows; r++) {
			Row row = sheet.getRow(r);
			if (row == null) {
				row = sheet.createRow(r);
			}
			List<String> rowLst = new ArrayList<String>();
			/* 循环Excel的列 */
			String flag = "";
			for (short c = 0; c < this.totalCells; c++) {
				Cell cell = row.getCell(c);
				String cellValue = "";
				if (cell == null) {
					flag +=cellValue;
					rowLst.add(cellValue);
					continue;
				}

				/* 处理数字型的,自动去零 */
				if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
					/* 在excel里,日 期也是数字,在此要进行判断 */
					if (HSSFDateUtil.isCellDateFormatted(cell)) {
						// cellValue = DatUtil
						// .get4yMdHms(cell.getDateCellValue());
						cellValue = cell.getDateCellValue().toString();
					} else {
						cellValue = getRightStr(cell.getNumericCellValue() + "");
					}
				}

				/* 处理字符串型 */
				else if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
//					if(cell.getStringCellValue().contains("（")&&cell.getStringCellValue().contains("）")){
//						cellValue = cell.getStringCellValue().replaceAll("（", "(").replaceAll("）", ")");
//					}else{
						cellValue = cell.getStringCellValue();
//					}
				}

				/* 处理布尔型 */
				else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
					cellValue = cell.getBooleanCellValue() + "";
				}

				/* 其它的,非以上几种数据类型 */
				else {
					cellValue = cell.toString() + "";
				}
				flag+=cellValue;
				rowLst.add(cellValue);
			}
			if("".equals(flag)){
            	continue;
            }
			dataLst.add(rowLst);
		}

		return dataLst;
	}

	public List<List<String>> readExport(String fileName) {
		List<List<String>> dataLst = null;//new ArrayList<ArrayList<String>>();

		/* 检查文件是否存在 */
		File file = new File(fileName);
		if (file == null || !file.exists()) {
			return dataLst;
		}

		/* 检查文件名是否 Excel 格式的文件 */
		String fn = fileName.substring(fileName.lastIndexOf(File.separator)+1);
		if (!fn.matches("^.+\\.(?i)((xls)|(xlsx))$")) {
			return dataLst;
		}

		boolean isExcel2003 = true;
		/* 对文件的合法性进行验证 */
		if (fn.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}


		try {
			/** 调用本类提供的根据流读取的方法 */
			dataLst = readExport(new FileInputStream(file), isExcel2003);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		/** */
		/** 返回最后读取的结果 */
		return dataLst;
	}

	/**
	 * 根据流读取Excel文件
	 * 
	 * @param inputStream
	 * @param isExcel2003
	 * @return
	 */
	public List<List<String>> readExport(InputStream inputStream, boolean isExcel2003) {
		List<List<String>> dataLst = null;
		try {
			/* 根据版本选择创建Workbook的方式 */
			Workbook wb = isExcel2003 ? new HSSFWorkbook(inputStream)
					: new SXSSFWorkbook(new XSSFWorkbook(inputStream),1000);
			dataLst = readExport(wb);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataLst;
	}
	private List<List<String>> readExport(Workbook wb) {
		List<List<String>> dataLst = new LinkedList<List<String>>();

		/* 得到第一个shell */  
		Sheet sheet = wb.getSheetAt(0);
		this.totalRows = sheet.getLastRowNum()+1;
		if (this.totalRows >= 1 && sheet.getRow(0) != null) {
			this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
		}
//		for(int i=0;i<this.totalRows;i++){
//			Row row = sheet.getRow(i);
//			if(row==null){
//				row = sheet.createRow(i);
//			}
//		}
		/* 循环Excel的行 */
		for (int r = 0; r < this.totalRows; r++) {
			Row row = sheet.getRow(r);
			if (row == null) {
				row = sheet.createRow(r);
			}
			List<String> rowLst = new ArrayList<String>();
			/* 循环Excel的列 */
			String flag = "";
			for (short c = 0; c < this.totalCells; c++) {
				Cell cell = row.getCell(c);
				String cellValue = "";
				if (cell == null) {
					flag +=cellValue;
					rowLst.add(cellValue);
					continue;
				}

				/* 处理数字型的,自动去零 */
				if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
					/* 在excel里,日 期也是数字,在此要进行判断 */
					if (HSSFDateUtil.isCellDateFormatted(cell)) {
						// cellValue = DatUtil
						// .get4yMdHms(cell.getDateCellValue());
						cellValue = cell.getDateCellValue().toString();
					} else {
						cellValue = cell.getNumericCellValue()+"";
					}
				}

				/* 处理字符串型 */
				else if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
//					if(cell.getStringCellValue().contains("（")&&cell.getStringCellValue().contains("）")){
//						cellValue = cell.getStringCellValue().replaceAll("（", "(").replaceAll("）", ")");
//					}else{
						cellValue = cell.getStringCellValue();
//					}
				}

				/* 处理布尔型 */
				else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
					cellValue = cell.getBooleanCellValue() + "";
				}

				/* 其它的,非以上几种数据类型 */
				else {
					cellValue = cell.toString() + "";
				}
				flag+=cellValue;

				rowLst.add(cellValue);
			}
		    if("".equals(flag)){
            	continue;
            }

			dataLst.add(rowLst);
		}

		return dataLst;
	}

	/**
	 * 正确地处理整数后自动加零的情况
	 * 
	 * @param sNum
	 * @return
	 */
	private String getRightStr(String sNum) {
		DecimalFormat decimalFormat = new DecimalFormat("#.000000");
		String resultStr = decimalFormat.format(new Double(sNum));
		if (resultStr.matches("^[-+]?\\d+\\.[0]+$")) {
			resultStr = resultStr.substring(0, resultStr.indexOf("."));
		}
		return resultStr;
	}
	
	
	public void write2(int page, int row, int column, Object v, Workbook wb){
		Sheet sheet = wb.getSheetAt(page);
		if(sheet==null){
			Sheet s= wb.createSheet();
			Row row1 = s.createRow(row);
			Cell cell1 = row1.createCell(column);
			cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell1.setCellValue("");
			write3(v, cell1);
		}else{
			Row rows = wb.getSheetAt(page).getRow(row);
			if(rows==null){
				rows = wb.getSheetAt(page).createRow(row);
				Cell cell = rows.createCell(column);
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue("");
				write3(v, cell);
			}else{
				Cell cell = wb.getSheetAt(page).getRow(row).getCell(column);
				if(cell==null){
					cell = wb.getSheetAt(page).getRow(row).createCell(column);
					cell.setCellType(HSSFCell.CELL_TYPE_STRING);
					cell.setCellValue("");
					write3(v, cell);
				}else{
					write3(v, cell);
				}
			}
		}
		
	}
	public void write3(Object v,Cell cell){
		if(v == null) {
			cell.setCellValue("");
		}else if(v instanceof Long){
			cell.setCellValue((Long)v);
		}else if(v instanceof Double){
			cell.setCellValue((Double)v);
		}else if(v instanceof Calendar){
			cell.setCellValue((Calendar)v);
		}else if(v instanceof Date){
			cell.setCellValue(((Date)v).toString());
		}else if(v instanceof Boolean){
			cell.setCellValue((Boolean)v);
		}else if(v instanceof Integer){
			cell.setCellValue((Integer)v);
		}else{
			cell.setCellValue(v.toString());
		}
	}
	public Workbook openTemplate(String fileName) {
		Workbook wb = null;

		File file = new File(fileName);
		if (file == null || !file.exists()) {
			return wb;
		}

		if (!fileName.matches("^.+\\.(?i)((xls)|(xlsx))$")) {
			return wb;
		}

//		boolean isExcel2003 = true;
//		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
//			isExcel2003 = false;
//		}

		try {
			boolean b = fileName.contains(".xlsx");
			System.out.println("---->"+b);
			if(b==true){
				XSSFWorkbook book = new XSSFWorkbook(new FileInputStream(file));
				wb = new SXSSFWorkbook(book, 1000);
			}else{
				wb = new HSSFWorkbook(new FileInputStream(file));
			}
			
//			wb = b==true?new SXSSFWorkbook(book, 1000):(isExcel2003?new HSSFWorkbook(new FileInputStream(file)):book);
//			wb = isExcel2003 ? new HSSFWorkbook(new FileInputStream(file)): new XSSFWorkbook(new FileInputStream(file));
//			XSSFWorkbook book = new XSSFWorkbook(new FileInputStream(file));
//			wb = new SXSSFWorkbook(book, 1000);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return wb;
	}
	
	public void saveIn(Workbook wb, String fn) throws Exception{
		File file = new File(fn);
		if (file != null && file.exists()) {
			throw new Exception("文件已存在!");
		}

//		HSSFWorkbook	XSSFWorkbook	
		if(file.createNewFile()){
			OutputStream os = new FileOutputStream(file);
			wb.write(os);
			os.close();
		}
	}
	
}
